<template>
	<t-drawer 
		class="t-dr" 
		:visible="visibleDesign" 
		:closable="false" 
		:fullscreen="fullscreen"
		:switchFullscreen="fullscreen" 
		@close="() => {$emit('cancel');}"
	>
		<a-spin :spinning="loading" :delay="delayTime">
			<div class="flex design-header">
				<div class="logo">
					<img :src="systemLogo" alt="logo">
					<div class="title">表单设计</div>
				</div>
				<div class="left-step" :style="leftStep">
					<a-steps :current="currentIndex" size="default">
						<a-step :title="item.name" v-for="(item, index) in stepList" :key="index" />
					</a-steps>
				</div>
				<div class="right-btn">
					<a-button class="buttonGray" icon="left" :disabled="true">
                        {{$ct("PreviousStep","上一步")}}
                    </a-button>
					<a-button class="buttonGray" icon="right" :disabled="true">
                        {{$ct("NextStep","下一步")}}
					</a-button>
					<a-button class="cu-btn-primary" icon="check" @click="handleSubmitData" :loading="loading">
                        {{$ct("save","保存")}}
                    </a-button>
					<a-button class="cancelBtn" icon="close" @click="handleClose">
                        {{$ct("close","关闭")}}
                    </a-button>
				</div>
			</div>
			<form-view 
                style="height: calc(100vh - 56px);" 
                ref="formView" 
                v-show="currentIndex === 2"
                :basicData="basicSetting" 
                :basicsUuid="basicsUuid" 
                :tName="tName" 
                :isEdit="isEdit" 
				:editLayout="editLayout"
                @close="() => {$emit('cancel');}" 
                @save="() => {$emit('ok');}" 
            />
		</a-spin>
	</t-drawer>
</template>

<script>
	import {mapGetters} from 'vuex'
	import formView from "@/components/TopVUI/k-form-design/packages/KFormDesign/form.vue";
	export default {
		components: {
			formView,
		},
		props: {
			visibleDesign: {
				type: Boolean,
			},
			model: {
				type: Object,
				default: () => null,
			},
			basicsUuid: {
				type: String,
				default: () => "",
			},
			formType: {
				type: String,
				default: () => ""
			},
			isEdit: {
				type: Boolean,
				default: () => false
			},
		},
		data() {
			return {
				fullscreen: true,
				currentIndex: 2,
				stepList: [{
						name: this.$ct("systemConfigIndex","基础配置"),
						key: 1,
					},
					{
						name: this.$ct("DataConfiguration","数据配置"),
						key: 2,
					},
					{
						name: this.$ct("FormDesign","表单设计"),
						key: 3,
					},
					{
						name: this.$ct("ListDesign","列表设计"),
						key: 4,
					}
				],
				basicSetting: {
					basicLayout: "default",
				},
				dataSource: [],
				activeKey: "1", //列表属性
				loading: false,
				delayTime: 500,
				tName: "",
				record: {},
				leftStep: {
					width: 'calc(70% - 160px)',
					padding: '0 10%'
				},
				formList: {},
				initialLoad: true,
				platformKey: "desktop",
				layoutData: {},
				editLayout: false,
			};
		},
		computed: {
			...mapGetters(['configData']),
			systemLogo(){
				let index = this.configData.findIndex(item => item.code === 'systemLogo')
				if(index>=0){
					return this.configData[index].value
				} else {
					return 'https://zysd-shanghai.oss-cn-shanghai.aliyuncs.com/emis/logo.png'
				}
			}
		},
		methods: {
			// 表单布局缺少传递的参数
			getData(record, params) {
				let formData = JSON.parse(record.databaseJson);
				let obj = {};
				if (!formData.dataSource) {
					obj = {
						type: formData.type,
						data: [{
							tableName: formData.tableName ? formData.tableName : '',
							tableRemarks: formData.tableRemarks ? formData.tableRemarks : '',
						}],
						fields: [],
					}
				} else {
					obj = {
						type: formData.type,
						data: formData.dataSource.map(item => {
							return {
								tableName: item.tableName,
								tableRemarks: item.tableRemarks
							}
						}),
						fields: [],
					}
				}
				setTimeout(() => {
					this.$refs.formView.fromDataConfig = obj;
				},200);
				this.record = record;
				this.layoutData = params;
				if ('fromJson' in params && params.fromJson !== null) {
					this.$nextTick(() => {
						const data = {
							designJson: params.fromJson,
							appFormData: params.fromJson,
							uuid: params.uuid
						}
						this.$refs.formView.loadData(data);
					})
				} else {
					this.$post("/form/formBasicConfigure/getDetailByUuid",{
						uuid: record.uuid
					}).then(res => {
						this.$refs.formView.loadData(res.formDesign);
						this.formList = res.formList
					})
				}
			},
			handleSubmitData() {
				const that = this;
				let formData = that.$refs.formView.getListData();
				let param = {
					fromJson: JSON.stringify(formData.webJson),
				};
				if(that.isEdit){
					const modal = that.$confirm({
						title: "提示",
						content: "保存或发布新版本",
						okText: "保存",
						closable: true,
						onOk() {
							param.newVersion = false
							that.handleSubmitSave(param)
						},
					});
				}else{
					that.handleSubmitSave(param)
				}
			},
			handleSubmitSave(param){
                const data = {
                    designJson: param.fromJson,
                    ...this.layoutData
                }
				this.loading = true;
				if (typeof data.uuid === 'undefined') {
					this.$post("/form/formLayout/save", data).then((res) => {
						if (res.statusCode === 200) {
							this.$message.success(res.message ? res.message : '保存成功！', 1.5);
							this.$emit('ok');
						} else {
							this.$message.error(res.message ? res.message : '保存失败', 1.5)
						}
						this.loading = false;
					});
				} else {
					this.$post("/form/formLayout/update", data).then((res) => {
						if (res.statusCode === 200) {
							this.$message.success(res.message ? res.message : '编辑成功！', 1.5);
							this.$emit('ok');
						} else {
							this.$message.error(res.message ? res.message : '编辑失败', 1.5)
						}
						this.loading = false;
					});
				}
			},
			//根据布局获取source
			getSourceDataByLayout(data) {
				let dataList = data?.list || data
				dataList.forEach((val) => {
					if (
						!~[
							"table",
							"grid",
							"tabs",
							"card",
							"batch",
							"divider",
							"text",
							"button",
							"alert",
							"html",
							"qrCode",
							"barCode",
							"videoPlayer",
							"hyperlink",
							"hyperlinkPro",
							"groupTitle",
							"blank"
						].indexOf(val.type)
					) {
						this.getSourceDataList(val); //数据push
					} else if (~["grid", "tabs"].indexOf(val.type)) {
						//栅格、选项卡布局
						val.columns.forEach((el) => {
							this.getSourceDataByLayout(el.list);
						});
					} else if (val.type == "card") {
						//卡片布局
						this.getSourceDataByLayout(val.list);
					} else if (val.type == "table") {
						//表格布局
						val.trs.forEach((tr) => {
							tr.tds.forEach((td) => {
								this.getSourceDataByLayout(td.list);
							});
						});
					}
				});
			},
			//获取数据
			getSourceDataList(val) {
				let obj = {
					filed: val.model,
					filedName: val.label,
					filedType: val.type,
					align: "left",
					fixed: "",
					width: null,
					type: "contain" // 列表设计查询方式
				};
				if(val.options.showTime){
					obj.showTime = true
				};
				this.dataSource.push(obj);
			},
			handleClose(){
				let that = this
				that.$confirm({
					title: '警告',
					content: '关闭后所有未保存的数据将会清空，请谨慎操作！',
					okText: '关闭',
					okType: 'danger',
					cancelText: '取消',
					onOk() {
						that.$emit('cancel');
						that.activeKey = '1';
						that.$refs.formView.data.list = [];
						that.$refs.formView.selectItem = { key: '' };
						that.$refs.formView.options = {};
					}
				})
			},
		},
	};
</script>

<style lang="less" scoped>
	@basehight: 56px;

	.buttonGray,.buttonGray:hover {
		color: #d9d9d9;
		margin-right: 10px;
		background: #fafafa;
	}

	.t-dr {
		.design-header {
			width: 100%;
			height: @basehight;
			line-height: @basehight;
			border-bottom: 1px solid #e8e8e8;
			background-color: #fff;

			.left-step {
				// width: 70%;
				// padding: 0 20%;

				.ant-steps {
					padding-top: 10px;
				}
			}
		}
	}

	/deep/ .ant-drawer-header,
	/deep/ .ant-drawer-body {
		padding: 0 !important;
	}

	.right-btn {
		width: 30%;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		padding-right: 20px;
	}

	/deep/.bpmn-viewer-container {
	  height: calc(100vh - 88px);
	}

	.cancelBtn{
		background: #E4746F !important;
		border-color: #E4746F !important;
		color: #fff;
	}

	.cancelBtn:hover{
		opacity: 0.9;
	}

	/deep/.ant-drawer-content{
		background-color: #F0F2F5;
	}

	.logo{
		width: 160px;
		padding-left: 45px;
		display: flex;
		align-items: center;
		img{
			width: 32px;
			height: 32px;
		}
		.title{
			font-weight: 500;
			display: inline;
			font-size: 16px;
			padding-left: 10px;
		}
	}
</style>
